package com.nanfangzhe.shirodemo.controller;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.nanfangzhe.shirodemo.config.ShiroService;
import com.nanfangzhe.shirodemo.entity.UUser;
import com.nanfangzhe.shirodemo.service.UUserService;

@RestController
@RequestMapping("/home")
public class HomeController {
	@Autowired
	UUserService userService;

	@Autowired
	ShiroService shiroService;

	@RequestMapping("/add")
	public String add(UUser user) {
		System.out.println(user.getUsername());
		UUser finduser = userService.getByUsername(user.getUsername());
		if (finduser != null)
			return "用户名已存在";
		if (userService.add(user))
			return "注册成功";
		return "其他错误";
	}

	@RequestMapping("/hello")
	public String hello() {
		return "你拥有hello的权限";
	}

	@RequestMapping("/no_login")
	public String no_login() {
		return "请先登录";
	}

	@RequestMapping("/hello2")
	public String hello2() {
		return "你拥有hello2的权限";
	}

	@RequestMapping("/logout")
	public String logout() {
		return "退出成功";
	}

	@RequestMapping("/login")
	public String login(UUser user) {
		if (StringUtils.isBlank(user.getUsername()) || StringUtils.isBlank(user.getPassword())) {
			return "帐号或密码不能为空";
		}
		// 获取当前的用户
		Subject subject = SecurityUtils.getSubject();
		// 封装用户的登录数据
		String password = DigestUtils.md5DigestAsHex(user.getPassword().getBytes());
		UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), password);
		try {
			subject.login(token); // 执行登录方法，如果没有异常就说明OK了
		} catch (UnknownAccountException e) { // 用户名不存在
			return "用户不存在";
		} catch (IncorrectCredentialsException e) { // 密码错误
			return "帐号或者密码错误";
		} catch (DisabledAccountException e) {
			return "该帐号已禁止登录！";
		}

		// 更新登录时间 last login time
		// user.setLastLoginTime(new Date());
		// sysUserService.updateById(user);
		return "登录成功";

	}

	@RequestMapping("/noauthor")
	public String noauthor() {
		return "没有该权限";
	}

	@RequestMapping("/back")
	public String back() {
		return "欢迎回家";
	}
	@RequestMapping("/update_author")
	public String update_author() {
		shiroService.updatePermission();
		return "更新权限成功！";
	}
}
